package com.friend.joey.applicationfriend.Fragments;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.friend.joey.applicationfriend.MainActivity;
import com.friend.joey.applicationfriend.Classes.MyBaiduSearch;
import com.friend.joey.applicationfriend.R;
import com.friend.joey.applicationfriend.Classes.Result;
import com.friend.joey.applicationfriend.Adapters.SearchAdaper;

import java.lang.ref.WeakReference;
import java.util.ArrayList;


/**
 * Created by Joey on 2017/4/20.
 */

public class FragmentSearch extends Fragment {
    private ImageButton btn_cserach;
    private EditText txt_cInput;
    private WebView web_view;
    private URLUtil url;
    private MainActivity mactivity;
    private Toolbar toolbar;
    private MyHandler mHandler;
    private MyBaiduSearch search;
    private SearchAdaper adapter;
    private RecyclerView searchRecyclerView;
    private LinearLayoutManager layoutManager;
    private ArrayList<Result> results = new ArrayList<Result>();//搜索结果列表
    private int total;
    private boolean loadfinish=false;
    private boolean isloading=false;
    //private InputMethodManager imm;

    private class MyHandler extends Handler {
        private WeakReference<MainActivity> mWeakReference;
        public MyHandler(MainActivity activity){
            mWeakReference=new WeakReference<MainActivity>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity activity= mWeakReference.get();
            if(activity!=null){
                switch(msg.what){
                    case 1:
                        //Toast.makeText(activity,msg.obj.toString(),Toast.LENGTH_SHORT).show();
                        addResults();
                        //textView.setText(msg.obj.toString());
                        break;
                    case 2:
                        Toast.makeText(activity,msg.obj.toString(), Toast.LENGTH_SHORT).show();
                        break;
                    case -1:
                        Toast.makeText(activity, "失败", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        Toast.makeText(activity, "没有信息", Toast.LENGTH_SHORT).show();
                }
            }
            else{
                Toast.makeText(activity, "错误", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search, container, false);
        mHandler = new MyHandler((MainActivity)getActivity());
        searchRecyclerView=(RecyclerView)view.findViewById(R.id.search_recycler_view);
        btn_cserach=(ImageButton)view.findViewById(R.id.button_csearch);
        txt_cInput=(EditText)view.findViewById(R.id.txt_cInput);
        mactivity =(MainActivity)getActivity();
        toolbar=(Toolbar)view.findViewById(R.id.toolbarSearch);//
        //imm = (InputMethodManager) mactivity.getSystemService(INPUT_METHOD_SERVICE);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //
        setHasOptionsMenu(true);
        if (toolbar != null) {
            toolbar.setTitle("  ");
            toolbar.setNavigationIcon(R.drawable.computer3);
        }
        mactivity.setSupportActionBar(toolbar);
        //展示搜索信息
        initResults();
        //Toast.makeText(mactivity, results.get(0).getString(), Toast.LENGTH_SHORT).show();
        layoutManager = new LinearLayoutManager(getContext());
        searchRecyclerView.setLayoutManager(layoutManager);
        adapter = new SearchAdaper(results);
        searchRecyclerView.setAdapter(adapter);
        results.remove(0);
        adapter.notifyItemRemoved(0);

        search=new MyBaiduSearch("苹果",results);
        btn_cserach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String keyword=txt_cInput.getText().toString();
                mactivity.imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
                if(keyword!="") {
                    results.clear();
                    search = new MyBaiduSearch(keyword, results);
                    searchThread();
                }
            }
        });
        searchRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //Toast.makeText(mactivity, Integer.toString(newState), Toast.LENGTH_SHORT).show();
                int lastItemPosition = layoutManager.findLastVisibleItemPosition();
                if(newState== 0 && lastItemPosition+1==results.size() && (!isloading) && loadfinish) {
                    isloading=true;
                    //Toast.makeText(mactivity,Integer.toString(mactivity.back), Toast.LENGTH_SHORT).show();
                    searchThread();
                }
            }
        });

    }
    private void searchThread(){
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run(){
                //search.run();
                Message message = mHandler.obtainMessage();
                message.what = -1;
                try{
                    search.run();
                    message.what=1;
                    message.obj=search.getResultString();
                    loadfinish=true;
                    isloading=false;
                    //initResults();
                    //results=search.getResults();
                }catch (Exception e){
                    message.obj=e.toString();
                }
                mHandler.sendMessage(message);
            }
        });
        thread.start();
    }
    private void initResults(){
        Result msg1= new Result("更多","上划加载。。。","#*$");
        results.add(msg1);
    }
    private void addResults(){
        adapter.notifyDataSetChanged();//有新消息时刷新显示
    }
    private void talkSearch(){
    }
    public void setTxt_cInput(String result){
        txt_cInput.setText(result);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                mactivity.showDrawer();
                break;
        }
        return true;
    }
    public static FragmentSearch newInstance(String arg){
        FragmentSearch FragmentSearch = new FragmentSearch();
        Bundle args = new Bundle();
        args.putString("fSearch", arg);
        FragmentSearch.setArguments(args);
        return FragmentSearch;
    }
}
